package com.srd.phone.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.shengrongdai.srd.R;
import com.srd.phone.bean.ResultInfo;
import com.srd.phone.bean.TenderInfo;
import com.srd.phone.bean.TenderInvestUserInfo;
import com.srd.phone.bean.TenderRewardInfo;
import com.srd.phone.dialog.ErrorAlertDialog;
import com.srd.phone.mvp.presenters.TenderInvestPresenter;
import com.srd.phone.utils.CommonUtils;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.LogUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投标,也是投资详情
 */
public class TenderInvestActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_yield; //收益率
    private TextView tv_refund_type; //还款方式
    private TextView tv_money; //借款金额
    private TextView tv_complete; //已投金额
    private TextView tv_time; //借款期限
    private TextView tv_undone; //还需金额
    private TextView tv_progress; //进度条值
    private ProgressBar my_progress;
    private TextView tv_detail; //标的项目简介
    private TextView tv_tender_record; //投资记录
    private EditText et_password;
    private Button bt_invest;//立即投资
    private EditText et_money;
    private TextView tv_reward_type; //奖励类型
    private TextView tv_reward_money;//奖励类型
    private LinearLayout ll_invest_bottom; //底部的投资父视图

    private TenderInfo info;
    private TenderInvestPresenter investPresenter;
    private String urlBmarkListDetails = Constants.BASEURL + "bmarkApp/bmarkDetails"; //投资详情
    private String getYmemberUrl = Constants.BASEURL + "ymemberControllerApp/getYmember"; // 获取用户可用金额
    private String getInvesActityListUrl = Constants.BASEURL + "hChronicleApp/getInvesActityList"; // 获取获取投资奖励
    private String hchronicleListUrl = Constants.BASEURL + "hChronicleApp/hchronicleList"; // 获取奖励金额
    private String bmarkToTrecordUrl = Constants.BASEURL + "trecordsApp/bmarkToTrecord";  //立即投资

    private TenderInvestUserInfo investUserInfo; //用户可用金额
    private List<TenderRewardInfo> rewardTypeList = new ArrayList<>(); //奖励类型
    private TenderRewardInfo selectedRewardTypeInfo;
    private List<TenderRewardInfo.RewareMoneyInfo> rewardMoneyList = new ArrayList<>(); //奖励金额
    private TenderRewardInfo.RewareMoneyInfo selectedRewardMoneyInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tender_invest);
        initView();
        initData();
    }

    @Override
    public void initView() {
        tv_common_title.setText("投资详情");
        tv_yield = (TextView) findViewById(R.id.tv_yield);
        tv_refund_type = (TextView) findViewById(R.id.tv_refund_type);
        tv_money = (TextView) findViewById(R.id.tv_money);
        tv_complete = (TextView) findViewById(R.id.tv_complete);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_undone = (TextView) findViewById(R.id.tv_undone);
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        my_progress = (ProgressBar) findViewById(R.id.my_progress);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        tv_detail.setOnClickListener(this);
        tv_tender_record = (TextView) findViewById(R.id.tv_tender_record);
        tv_tender_record.setOnClickListener(this);
        bt_invest = (Button) findViewById(R.id.bt_invest);
        bt_invest.setOnClickListener(this);
        et_money = (EditText) findViewById(R.id.et_money);
        tv_reward_type = (TextView) findViewById(R.id.tv_reward_type);
        tv_reward_type.setOnClickListener(this);
        tv_reward_money = (TextView) findViewById(R.id.tv_reward_money);
        tv_reward_money.setOnClickListener(this);
        ll_invest_bottom = (LinearLayout) findViewById(R.id.ll_invest_bottom);
        et_password = (EditText) findViewById(R.id.et_password);
    }

    private int tenderInfoId;

    @Override
    public void initData() {
        info = (TenderInfo) getIntent().getSerializableExtra("info");
        tenderInfoId = info.id;
        presenter = new TenderInvestPresenter(requestQueue, this);
        investPresenter = (TenderInvestPresenter) presenter;
        setUrlArrs(urlBmarkListDetails, bmarkToTrecordUrl, getYmemberUrl, getInvesActityListUrl, getYmemberUrl);
        getYmember(); //获取用户可用余额
        getTenderInfo(); //获取投资详情
    }

    private void setData() {
        if (info == null)
            return;
        investPresenter.setTenderTextSpan(tv_yield, CommonUtils.getDecimalFormatFirst(info.anyield), "%");
        tv_refund_type.setText(info.nnm);

        tv_money.setText("借款金额：" + investPresenter.getFormatMoney(info.moneys));
        tv_complete.setText("已投金额：" + investPresenter.getFormatMoney(info.total));

        if (info.timetpm.contains("月")) {
            tv_time.setText("借款期限：" + info.term + "个" + info.timetpm);
        } else {
            tv_time.setText("借款期限：" + info.term + info.timetpm);
        }

        tv_undone.setText("还需金额：" + investPresenter.getFormatMoney(info.moneys - info.total));
        tv_progress.setText((int) info.subSch + "%");
        my_progress.setProgress((int) info.subSch);
        if (info.stat == 62) {
            ll_invest_bottom.setVisibility(View.GONE);
            et_password.setVisibility(View.GONE);
        } else {
            ll_invest_bottom.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(info.directional)) {
                et_password.setVisibility(View.GONE);
            } else {
                et_password.setVisibility(View.VISIBLE);
            }
        }
    }

    //获取投资详情
    private void getTenderInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("id", tenderInfoId + "");
        investPresenter.requestPostData(urlBmarkListDetails, map);
    }

    //获取用户可用金额
    private void getYmember() {
        investPresenter.requestPostData(getYmemberUrl);
    }

    //获取投资奖励
    private void getInvestReward() {
        showWaitingDialog();
        Map<String, String> map = new HashMap<>();
        map.put("did", "23");
        map.put("outId", "44");
        investPresenter.requestPostData(getInvesActityListUrl, map);
    }

    //获取奖励类别下的奖励金额
    private void getRewardMoney() {
        if (selectedRewardTypeInfo == null) {
            Toast.makeText(mContext, "请选择奖励类型", Toast.LENGTH_SHORT).show();
            return;
        }
        showWaitingDialog();
        Map<String, String> map = new HashMap<>();
        map.put("moneys", info.moneys + "");
        map.put("isover", "1");
        map.put("state", "1");
        map.put("tyid", selectedRewardTypeInfo.id + "");
        investPresenter.requestPostData(hchronicleListUrl, map);
    }

    //立即投资
    private void investTender() {
        String etMoney = et_money.getText().toString();
        String etPassword = et_password.getText().toString();
        if (TextUtils.isEmpty(etMoney)) {
            etMoney = "0";
        }
        double value = Double.parseDouble(etMoney);
        if (value == 0) {
            moneyDialog();
            return;
        }

        if (selectedRewardMoneyInfo != null) {
            value = value + Double.parseDouble(selectedRewardMoneyInfo.money);
        }

        String checkValue = investPresenter.checkValue(value, info, etPassword);
        if (!TextUtils.isEmpty(checkValue)) {
            Toast.makeText(mContext, checkValue, Toast.LENGTH_SHORT).show();
            return;
        }

        showWaitingDialog();
        Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(info.id));
        map.put("upperm", String.valueOf(info.upperm));
        map.put("floorm", String.valueOf(info.floorm));
        map.put("uMoney", value + "");
        map.put("moneys", String.valueOf(info.moneys));
        map.put("tcount", String.valueOf(info.tcount));
        map.put("directional", String.valueOf(info.directional));
        map.put("anyield", String.valueOf(info.anyield));
        map.put("numbers", String.valueOf(info.numbers));
        map.put("term", String.valueOf(info.term));
        map.put("timetp", String.valueOf(info.timetp));
        map.put("tid", String.valueOf(info.tid));
        map.put("total", String.valueOf(info.total));
        if (selectedRewardTypeInfo != null && selectedRewardMoneyInfo != null) {
            map.put("tyid", String.valueOf(selectedRewardTypeInfo.id)); //奖励类别id
            map.put("money", String.valueOf(selectedRewardMoneyInfo.money)); //奖励物品金额/加息率
            map.put("hcronid", selectedRewardMoneyInfo.id + "");
        }
        if (!TextUtils.isEmpty(info.directional)) {
            if (TextUtils.isEmpty(etPassword)) {
                Toast.makeText(mContext, "定向标密码不能为空", Toast.LENGTH_SHORT).show();
            } else {
                map.put("bmarkPass", String.valueOf(etPassword)); //录入定向标的密码
            }
        }
        investPresenter.requestPostData(bmarkToTrecordUrl, map);

        bt_invest.setEnabled(false);
    }

    @Override
    public void returnData(String tag, String data) {
        super.returnData(tag, data);
        LogUtils.i(TenderInvestActivity.class, data);
        cancelWaitingDialog();
        if (tag == urlBmarkListDetails) { //获取投资详情
            info = TenderInfo.parseTenderInfoData(data);
            setData();
        } else if (tag == getYmemberUrl) { //获取可用金额
            investUserInfo = TenderInvestUserInfo.parse(data);
            et_money.setText(investUserInfo.account + "");
        } else if (tag == bmarkToTrecordUrl) { //立即投资
            clearRewardMoney();
            ResultInfo resultInfo = ResultInfo.parse(data);
            if (resultInfo.code == 300) {
                gotoActivity(TenderSuccessActivity.class);
                finish();
                return;
            } else if (resultInfo.code == 213) { //定向标密码锁定
                leadTenderDialog();
                return;
            }
            Toast.makeText(TenderInvestActivity.this, resultInfo.msg, Toast.LENGTH_SHORT).show();
        } else if (tag == getInvesActityListUrl) { //获取投资奖励列表
            rewardTypeList = TenderRewardInfo.parseRewardType(data);
            showRewardTypeDailog();
        } else if (tag == hchronicleListUrl) { //获取奖励金额
            rewardMoneyList = TenderRewardInfo.parseRewardMoney(data);
            showRewardMoneyDialog();
        }
    }

    @Override
    public void onError(String tag, VolleyError error) {
        super.onError(tag, error);
        bt_invest.setEnabled(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_tender_record:
                Intent intent = new Intent(mContext, TenderRecordDetailActivity.class);
                intent.putExtra("info", info);
                startActivity(intent);
                break;
            case R.id.bt_invest:
                investTender();
                //intent = new Intent(mContext, TenderInvestPwdActivity.class);
                //startActivity(intent);
                break;
            case R.id.tv_detail:
                intent = new Intent(mContext, TenderDetailActivity.class);
                intent.putExtra("info", info);
                startActivity(intent);
                break;
            case R.id.tv_reward_type:
                if (rewardTypeList.size() == 0) {
                    getInvestReward();
                } else {
                    showRewardTypeDailog();
                }
                break;
            case R.id.tv_reward_money:
                if (rewardMoneyList.size() == 0) {
                    getRewardMoney();
                } else {
                    showRewardMoneyDialog();
                }
                break;
        }
    }


    List<String> list1 = new ArrayList<>();

    //奖励类型
    private void showRewardTypeDailog() {
        list1.clear();
        list1.add("奖励类型");
        for (TenderRewardInfo info : rewardTypeList) {
            list1.add(info.nm);
        }
        Intent intent = new Intent(mContext, DialogListViewActivity.class);
        intent.putExtra("list", (Serializable) list1);
        startActivityForResult(intent, 1000);
    }

    List<String> list2 = new ArrayList<>();

    //奖励金额
    private void showRewardMoneyDialog() {
        list2.clear();
        list2.add("奖励金额");
        for (TenderRewardInfo.RewareMoneyInfo info : rewardMoneyList) {
            list2.add(info.money + "元");
        }
        Intent intent = new Intent(mContext, DialogListViewActivity.class);
        intent.putExtra("list", (Serializable) list2);
        startActivityForResult(intent, 2000);
    }

    //取消本地奖励金额数据
    private void clearRewardMoney() {
        rewardMoneyList.clear();
        list2.clear();
        selectedRewardMoneyInfo = null;
        tv_reward_money.setText("奖励金额");
        bt_invest.setEnabled(true);
    }

    ErrorAlertDialog alertDialog;

    //充值提示框
    private void moneyDialog() {
        alertDialog = new ErrorAlertDialog(mContext, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setText("金额不能为空，是否去充值？");
        alertDialog.show();
    }

    //定向标密码提示框
    private void leadTenderDialog() {
        alertDialog = new ErrorAlertDialog(mContext, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:13850734494"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        alertDialog.show();
        alertDialog.setText("定向标密码错误超过三次，是否去联系客服？");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1000 && data != null) { //奖励类型
            if (resultCode == 0) {
                selectedRewardTypeInfo = null;
                tv_reward_type.setText(list1.get(0));
            } else {
                selectedRewardTypeInfo = rewardTypeList.get(resultCode - 1);
                tv_reward_type.setText(selectedRewardTypeInfo.nm);
            }
        } else if (requestCode == 2000 && data != null) { //奖励金额
            if (resultCode == 0) {
                selectedRewardMoneyInfo = null;
                tv_reward_money.setText(list2.get(0));
            } else {
                selectedRewardMoneyInfo = rewardMoneyList.get(resultCode - 1);
                tv_reward_money.setText(selectedRewardMoneyInfo.money);
            }
        }
    }
}
